package com.seisys.controller.system.user;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.seisys.controller.base.BaseController;
import com.seisys.entity.Page;
import com.seisys.entity.system.Role;
import com.seisys.entity.system.SubLineRole;
import com.seisys.entity.system.User;
import com.seisys.service.system.LogService;
import com.seisys.service.system.menu.MenuService;
import com.seisys.service.system.role.RoleService;
import com.seisys.service.system.user.UserService;
import com.seisys.util.AppUtil;
import com.seisys.util.Const;
import com.seisys.util.FileDownload;
import com.seisys.util.FileUpload;
import com.seisys.util.GetPinyin;
import com.seisys.util.IData;
import com.seisys.util.Jurisdiction;
import com.seisys.util.LogUtil;
import com.seisys.util.ObjectExcelRead;
import com.seisys.util.ObjectExcelView;
import com.seisys.util.PageData;
import com.seisys.util.PathUtil;
import com.seisys.util.Tools;

import net.sf.json.JSONArray;


/**
 * 类名称：UserController 创建人：FH 创建时间：2014年6月28日
 * 
 * @version
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController
{
    private static final String MODULENAME = "系统用户";

    String menuUrl = "user/listUsers.do"; // 菜单地址(权限用)

    @Resource(name = "userService")
    private UserService userService;

    @Resource(name = "roleService")
    private RoleService roleService;

    @Resource(name = "menuService")
    private MenuService menuService;

    @Resource(name = "logService")
    private LogService logService;

    /**
     * 保存用户
     */
    @RequestMapping(value = "/saveU")
    public ModelAndView saveU()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();

        pd.put("USER_ID", this.get32UUID()); // ID
        pd.put("RIGHTS", ""); // 权限
        pd.put("LAST_LOGIN", ""); // 最后登录时间
        pd.put("IP", ""); // IP
        pd.put("STATUS", "0"); // 状态

        pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"),
            pd.getString("PASSWORD")).toString());

        if (null == userService.findByUId(pd))
        {
            if (Jurisdiction.buttonJurisdiction(menuUrl, "add"))
            {
                userService.saveU(pd); // 判断新增权限
            }
            mv.addObject("msg", "success");
        }
        else
        {
            mv.addObject("msg", "failed");
        }
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 判断用户名是否存在
     */
    @RequestMapping(value = "/hasU")
    @ResponseBody
    public Object hasU()
    {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        PageData pd = new PageData();
        try
        {
            pd = this.getPageData();
            if (userService.findByUId(pd) != null)
            {
                errInfo = "error";
            }
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        map.put("result", errInfo); // 返回结果
        return AppUtil.returnObject(new PageData(), map);
    }

    /**
     * 判断邮箱是否存在
     */
    @RequestMapping(value = "/hasE")
    @ResponseBody
    public Object hasE()
    {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        PageData pd = new PageData();
        try
        {
            pd = this.getPageData();

            if (userService.findByUE(pd) != null)
            {
                errInfo = "error";
            }
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        map.put("result", errInfo); // 返回结果
        return AppUtil.returnObject(new PageData(), map);
    }

    /**
     * 判断编码是否存在
     */
    @RequestMapping(value = "/hasN")
    @ResponseBody
    public Object hasN()
    {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        PageData pd = new PageData();
        try
        {
            pd = this.getPageData();
            if (userService.findByUN(pd) != null)
            {
                errInfo = "error";
            }
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        map.put("result", errInfo); // 返回结果
        return AppUtil.returnObject(new PageData(), map);
    }

    /**
     * 修改用户
     */
    @RequestMapping(value = "/editU")
    public ModelAndView editU()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        if (pd.getString("PASSWORD") != null && !"".equals(pd.getString("PASSWORD")))
        {
            pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"),
                pd.getString("PASSWORD")).toString());
        }
        if (Jurisdiction.buttonJurisdiction(menuUrl, "edit"))
        {
            userService.editU(pd);
        }
        mv.addObject("msg", "success");
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * Description: (必填) 1、修改用户信息(后版本)
     * 
     * @param pd
     * @return ajax消息
     * @throws Exception
     * @see
     */
    @ResponseBody
    @RequestMapping(value = "/updateSystemRole")
    public Object updateSystemRole(@RequestBody PageData pd)
        throws Exception
    {
        Map<String, Object> result = new HashMap<>();

        try
        {
            if (pd.getString("PASSWORD") != null && !"".equals(pd.getString("PASSWORD")))
            {
                pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"),
                    pd.getString("PASSWORD")).toString());
            }
            if (Jurisdiction.buttonJurisdiction(menuUrl, "edit"))
            {
                userService.editU(pd);
                result.put("msg", "ok");
                LogUtil.getInstance().operationLogger(LogUtil.UPDATE, MODULENAME,
                    pd.getString("USER_ID"), logService, request);
                result.put("message", "修改成功");
            }
            else
            {
                result.put("msg", "ok");
                result.put("message", "没有修改权限");
            }
        }
        catch (Exception e)
        {
            result.put("msg", "ok");
            result.put("message", "修改失败");
            throw new RuntimeException("修改用户信息 用户系统角色出错！", e);
        }
        return result;
    }

    /**
     * 修改用户密码
     */
    @RequestMapping(value = "/editPwd")
    public ModelAndView editPwd()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        if (pd.getString("pwd") != null && !"".equals(pd.getString("pwd")))
        {
            pd.put("PASSWORD",
                new SimpleHash("SHA-1", pd.getString("userName"), pd.getString("pwd")).toString());
        }
        if (Jurisdiction.buttonJurisdiction(menuUrl, "edit"))
        {
            userService.editPwd(pd);
        }
        mv.addObject("msg", "success");
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 跳转修改密码页面
     */
    @RequestMapping(value = "/goUpdatePwdPage")
    public ModelAndView updatePwd()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User)session.getAttribute(Const.SESSION_USER);
        pd.put("USER_ID", user.getUSER_ID());
        pd = userService.findByUiId(pd); // 根据ID读取
        mv.setViewName("system/user/userUpdatePwd");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 跳转个人信息页面
     */
    @RequestMapping(value = "/goUserInfoPage")
    public ModelAndView goUserInfoPage()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User)session.getAttribute(Const.SESSION_USER);
        pd.put("USER_ID", user.getUSER_ID());
        pd = userService.findByUiId(pd); // 根据ID读取
        List<Role> roleList = roleService.listAllERRoles(); // 列出所有二级角色
        mv.addObject("roleList", roleList);
        mv.setViewName("system/user/user_info");
        mv.addObject("msg", "editU");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * Description: (必填) 1、去修改用户页面 2、带数据回显
     * 
     * @return
     * @throws Exception
     * @see
     */
    @RequestMapping(value = "/goEditU")
    public ModelAndView goEditU()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();

        // 顶部修改个人资料
        String fx = pd.getString("fx");

        if ("head".equals(fx))
        {
            mv.addObject("fx", "head");
        }
        else
        {
            mv.addObject("fx", "user");
        }
        try
        {
            pd = userService.findByUiId(pd); // 根据ID读取

        }
        catch (Exception e)
        {
            throw new RuntimeException("去修改用户页面出错！", e);
        }

        mv.setViewName("system/user/user_edit");
        mv.addObject("msg", "editU");
        mv.addObject("pd", pd);

        return mv;
    }

    /**
     * Description: (必填) 1、获取已保存的系统菜单 角色信息 2、
     * 
     * @return
     * @throws Exception
     * @see
     */
    @ResponseBody
    @RequestMapping(value = "/showUserSysRoles")
    public Object showUserSysRoles()
        throws Exception
    {
        Map<String, Object> result = new HashMap<>();
        PageData pd = new PageData();
        pd = this.getPageData();
        List<PageData> userSysRoles = new ArrayList<>();
        try
        {
            userSysRoles = userService.findUserSysRoleByUiId(pd);
            result.put("msg", "ok");
            result.put("userSysRoles", userSysRoles);
        }
        catch (Exception e)
        {
            throw new RuntimeException("获取已保存的系统菜单 角色信息出错!", e);
        }
        return result;
    }

    /**
     * 去新增用户页面
     */
    @RequestMapping(value = "/goAddU")
    public ModelAndView goAddU()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        List<Role> roleList;

        roleList = roleService.listAllERRoles(); // 列出所有二级角色

        mv.setViewName("system/user/user_edit");
        mv.addObject("msg", "saveU");
        mv.addObject("pd", pd);
        mv.addObject("roleList", roleList);

        return mv;
    }

    /**
     * Description: (必填) 1、获取子系统名称 2、获取除了系统管理员角色
     * 
     * @return
     * @throws Exception
     * @see
     */
    @RequestMapping(value = "/getsubSysData")
    @ResponseBody
    public Object getsubSysData()
        throws Exception
    {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> lineMap = new HashMap<>();
        List<Map<String,Object>> sublines = new ArrayList<Map<String,Object>>();

        // 角色
        List<Role> roles = roleService.showRoleInf();
        result.put("roles", roles);
        // 子系统
        List<IData> subsyses = userService.showSubSystem();
        result.put("subsyses", subsyses);
        
        //子线路系统及角色
        List<SubLineRole> subLine = roleService.showLineRoleinfo();
//        for (SubLineRole slr :lineRoles) {
//        	if(!lineMap.containsValue(slr.getLineId()))
//        	{
//        		lineMap = new HashMap<>();
//        		lineMap.put("lineId", slr.getLineId());
//        		lineMap.put("lineName", slr.getLineName());
//        		lineMap.put("menuId", slr.getMenuId());
//        		sublines.add(lineMap);
//        	}
//		}
        result.put("lineRoles", roles);
        result.put("subLines", subLine);
        return result;
    }

    /**
     * Description: (必填) 1、保存用户角色系统
     * 
     * @param user
     * @return
     * @throws Exception
     * @see
     */
    @ResponseBody
    @RequestMapping(value = "/saveSystemRole")
    public Object saveSystemRole(@RequestBody PageData pd)
        throws Exception
    {
        Map<String, Object> result = new HashMap<>();

        pd.put("USER_ID", this.get32UUID()); // ID
        pd.put("RIGHTS", ""); // 权限
        pd.put("LAST_LOGIN", ""); // 最后登录时间
        pd.put("IP", ""); // IP
        pd.put("STATUS", "0"); // 状态

        try
        {
            pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"),
                pd.getString("PASSWORD")).toString());

            if (null == userService.findByUId(pd))
            {
                if (Jurisdiction.buttonJurisdiction(menuUrl, "add"))
                {
                    userService.saveU(pd); // 判断新增权限
                    LogUtil.getInstance().operationLogger(LogUtil.ADD, MODULENAME,
                        pd.getString("USER_ID"), logService, request);
                }
                result.put("msg", "ok");
                result.put("message", "保存成功");
            }
            else
            {
                result.put("msg", "error");
                result.put("message", "保存失败");
            }
        }
        catch (Exception e)
        {
            result.put("msg", "error");
            result.put("message", "保存失败");
            throw new RuntimeException("保存用户角色系统出错！", e);
        }

        return result;
    }

    /**
     * 去新增用户页面
     */
    @RequestMapping(value = "/openSubSystem")
    public ModelAndView openSubSystem()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        IData param = IData.getInstance(request);
        String user_id = param.get("user_id").toString();
        mv.setViewName("system/user/user_subSystem");
        mv.addObject("user_id", user_id);
        return mv;
    }

    @RequestMapping(value = "/treeData")
    @ResponseBody
    public Map<String, Object> getAreaTreeData(HttpServletRequest request,
                                               HttpServletResponse response)
        throws Exception
    {
        boolean success = true;
        String msg = "";
        String json = "";
        Map<String, Object> result = new HashMap<String, Object>();
        try
        {
            List<IData> list = userService.listTreeData();
            JSONArray arr = JSONArray.fromObject(list);
            json = arr.toString();
            json = json.replaceAll("MENU_ID", "id").replaceAll("MENU_NAME", "name");
            result.put("zTreeNodes", json);
        }
        catch (Exception e)
        {
            success = false;
            msg = "网络请求失败";
        }
        result.put("success", success);
        result.put("msg", msg);
        return result;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("saveSubSys")
    @ResponseBody
    public Object saveSubSys()
        throws Exception
    {
        IData param = IData.getInstance(request);
        Map<String, Object> result = new HashMap<>();
        String menu_ids = param.get("menu_ids").toString();
        if (null != menu_ids && !"".equals(menu_ids))
        {
            String[] ArrayMenu_ids = menu_ids.split(",");
            param.put("menu_ids", ArrayMenu_ids);
            userService.deleteSubSys(param);
            userService.insertSubSys(param);
            result.put("isSuccess", true);
        }

        return result;
    }

    /**
     * 显示用户列表(用户组)
     */
    @RequestMapping("/userTable")
    @ResponseBody
    public Map<String, Object> userTable(int page, int size, String userName,
                                         String lastLoginStart, String lastLoginEnd,
                                         String role_id, String del_flag)
        throws UnsupportedEncodingException
    {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
//        int start = 1 + (size * (page - 1));
//        int end = page * size;
        Page pg = new Page();
        pg.setCurrentPage(page);
        pg.setShowCount(size);
        PageData pd = new PageData();
//        param.put("start", start);
//        param.put("end", end);
        pd.put("userName", userName);
        pd.put("lastLoginStart", lastLoginStart);
        pd.put("lastLoginEnd", lastLoginEnd);
        pd.put("ROLE_ID", role_id);
        pd.put("del_flag", del_flag);
        pg.setPd(pd);
        try
        {
//            List<User> userList = userService.listMapUser(param); // 列出用户列表
        	List<User> userList = userService.findUserListMap(pg); // 列出用户列表
        	map.put("rows", userList);
        	map.put("total", pg.getTotalResult());
//            Integer count = userService.countSearchUser(param);
//            map.put("rows", userList);
//            map.put("total", count);

        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }

        return map;
    }

    /**
     * Description: (必填) 1、恢复用户
     * 
     * @return
     * @throws Exception
     * @see
     */
    @ResponseBody
    @RequestMapping(value = "/revertUser")
    public String revertUser()
        throws Exception
    {
        String result = "";
        IData param = IData.getInstance(request);
        try
        {
            userService.revertUser(param);
            result = "success";
        }
        catch (Exception e)
        {
            throw new RuntimeException("恢复用户报错!", e);
        }
        return result;
    }

    /**
     * 显示用户列表(用户组)
     */
    @RequestMapping(value = "/listUsers")
    public ModelAndView listUsers(Page page)
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();

        String USERNAME = pd.getString("USERNAME");

        if (null != USERNAME && !"".equals(USERNAME))
        {
            USERNAME = USERNAME.trim();
            pd.put("USERNAME", USERNAME);
        }

        String lastLoginStart = pd.getString("lastLoginStart");
        String lastLoginEnd = pd.getString("lastLoginEnd");

        if (lastLoginStart != null && !"".equals(lastLoginStart))
        {
            lastLoginStart = lastLoginStart + " 00:00:00";
            pd.put("lastLoginStart", lastLoginStart);
        }
        if (lastLoginEnd != null && !"".equals(lastLoginEnd))
        {
            lastLoginEnd = lastLoginEnd + " 00:00:00";
            pd.put("lastLoginEnd", lastLoginEnd);
        }

        page.setPd(pd);
        List<PageData> userList = userService.listPdPageUser(page); // 列出用户列表
        List<Role> roleList = roleService.listAllERRoles(); // 列出所有二级角色

        mv.setViewName("system/user/user_list");
        mv.addObject("userList", userList);
        mv.addObject("roleList", roleList);
        mv.addObject("pd", pd);
        mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限
        return mv;
    }

    /**
     * demo_liuwei
     * 
     * @param page
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/bootstrap")
    public ModelAndView bootstrapdemo(Page page)
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("codeSamples/bootstrap_table");
        return mv;
    }

    /**
     * demo_liuwei
     * 
     * @param page
     * @param size
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/listUsers1")
    @ResponseBody
    public Map<String, Object> testTable(int page, int size, int key, HttpServletRequest request)
        throws UnsupportedEncodingException
    {
        request.setCharacterEncoding("UTF-8");
        System.out.println(key);
        Map<String, Object> param = new HashMap<String, Object>();
        int start = 1 + (size * (page - 1));
        int end = page * size;
        param.put("start", start);
        param.put("end", end);

        Map<String, Object> result = new HashMap<String, Object>();
        List<User> dd = userService.listAllUserbyTable(param);
        result.put("rows", dd);
        result.put("total", 5);
        return result;
    }

    /**
     * 显示用户列表(tab方式)
     */
    @RequestMapping(value = "/listtabUsers")
    public ModelAndView listtabUsers(Page page)
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        List<PageData> userList = userService.listAllUser(pd); // 列出用户列表
        mv.setViewName("system/user/user_tb_list");
        mv.addObject("userList", userList);
        mv.addObject("pd", pd);
        mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限
        return mv;
    }

    /**
     * 删除用户
     */
    @RequestMapping(value = "/deleteU")
    @ResponseBody
    public String deleteU()
    {
        PageData pd = new PageData();
        try
        {
            pd = this.getPageData();
            if (Jurisdiction.buttonJurisdiction(menuUrl, "del"))
            {
                userService.deleteU(pd);
                LogUtil.getInstance().operationLogger(LogUtil.DELETE, MODULENAME,
                    pd.getString("USER_ID"), logService, request);
            }
//            out.write("success");
//            out.close();
            return "success";
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
            return "error";
        }

    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/deleteAllU")
    @ResponseBody
    public Object deleteAllU()
    {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try
        {
            pd = this.getPageData();
            List<PageData> pdList = new ArrayList<PageData>();
            String USER_IDS = pd.getString("USER_IDS");

            if (null != USER_IDS && !"".equals(USER_IDS))
            {
                String ArrayUSER_IDS[] = USER_IDS.split(",");
                if (Jurisdiction.buttonJurisdiction(menuUrl, "del"))
                {
                    userService.deleteAllU(ArrayUSER_IDS);
                    LogUtil.getInstance().operationLogger("批量" + LogUtil.DELETE, MODULENAME,
                        pd.getString("USER_ID"), logService, request);
                }
                pd.put("msg", "ok");
            }
            else
            {
                pd.put("msg", "no");
            }

            pdList.add(pd);
            map.put("list", pdList);
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        finally
        {
            logAfter(logger, "");
        }
        return AppUtil.returnObject(pd, map);
    }

    /**
     * Description: (必填) 1、当前用户下系统菜单和用户角色 2、个人信息下展示
     * 
     * @return
     * @throws Exception
     * @see
     */
    @ResponseBody
    @RequestMapping(value = "/showusermenurole")
    public Object showusermenurole()
        throws Exception
    {
        Map<String, Object> result = new HashMap<>();
        IData param = IData.getInstance(request);
        try
        {
            List<IData> bo = userService.showusermenurole(param);
            result.put("userSysRole", bo);
            result.put("msg", "ok");
        }
        catch (Exception e)
        {
            throw new RuntimeException("查询当前用户下系统菜单和用户角色出错！", e);
        }
        return result;
    }
    // ===================================================================================================

    /*
     * 导出用户信息到EXCEL
     * @return
     */
    @RequestMapping(value = "/excel")
    public ModelAndView exportExcel()
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try
        {
            if (Jurisdiction.buttonJurisdiction(menuUrl, "cha"))
            {
                // 检索条件===
                String USERNAME = pd.getString("USERNAME");
                if (null != USERNAME && !"".equals(USERNAME))
                {
                    USERNAME = USERNAME.trim();
                    pd.put("USERNAME", USERNAME);
                }
                String lastLoginStart = pd.getString("lastLoginStart");
                String lastLoginEnd = pd.getString("lastLoginEnd");
                if (lastLoginStart != null && !"".equals(lastLoginStart))
                {
                    lastLoginStart = lastLoginStart + " 00:00:00";
                    pd.put("lastLoginStart", lastLoginStart);
                }
                if (lastLoginEnd != null && !"".equals(lastLoginEnd))
                {
                    lastLoginEnd = lastLoginEnd + " 00:00:00";
                    pd.put("lastLoginEnd", lastLoginEnd);
                }
                // 检索条件===

                Map<String, Object> dataMap = new HashMap<String, Object>();
                List<String> titles = new ArrayList<String>();

                titles.add("用户名"); // 1
                titles.add("编号"); // 2
                titles.add("姓名"); // 3
                titles.add("职位"); // 4
                titles.add("手机"); // 5
                titles.add("邮箱"); // 6
                titles.add("最近登录"); // 7
                titles.add("上次登录IP"); // 8

                dataMap.put("titles", titles);

                List<PageData> userList = userService.listAllUser(pd);
                List<PageData> varList = new ArrayList<PageData>();
                for (int i = 0; i < userList.size(); i++ )
                {
                    PageData vpd = new PageData();
                    vpd.put("var1", userList.get(i).getString("USERNAME")); // 1
                    vpd.put("var2", userList.get(i).getString("NUMBER")); // 2
                    vpd.put("var3", userList.get(i).getString("NAME")); // 3
                    vpd.put("var4", userList.get(i).getString("ROLE_NAME")); // 4
                    vpd.put("var5", userList.get(i).getString("PHONE")); // 5
                    vpd.put("var6", userList.get(i).getString("EMAIL")); // 6
                    vpd.put("var7", userList.get(i).getString("LAST_LOGIN")); // 7
                    vpd.put("var8", userList.get(i).getString("IP")); // 8
                    varList.add(vpd);
                }
                dataMap.put("varList", varList);
                ObjectExcelView erv = new ObjectExcelView(); // 执行excel操作
                mv = new ModelAndView(erv, dataMap);
            }
        }
        catch (Exception e)
        {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 打开上传EXCEL页面
     */
    @RequestMapping(value = "/goUploadExcel")
    public ModelAndView goUploadExcel()
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("system/user/uploadexcel");
        return mv;
    }

    /**
     * 下载模版
     */
    @RequestMapping(value = "/downExcel")
    public void downExcel(HttpServletResponse response)
        throws Exception
    {

        FileDownload.fileDownload(response,
            PathUtil.getClasspath() + Const.FILEPATHFILE + "Users.xls", "Users.xls");

    }

    /**
     * 从EXCEL导入到数据库
     */
    @RequestMapping(value = "/readExcel")
    public ModelAndView readExcel(@RequestParam(value = "excel", required = false) MultipartFile file)
        throws Exception
    {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "add"))
        {
            return null;
        }
        if (null != file && !file.isEmpty())
        {
            String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE; // 文件上传路径
            String fileName = FileUpload.fileUp(file, filePath, "userexcel"); // 执行上传

            List<PageData> listPd = (List)ObjectExcelRead.readExcel(filePath, fileName, 2, 0, 0); // 执行读EXCEL操作,读出的数据导入List
                                                                                                  // 2:从第3行开始；0:从第A列开始；0:第0个sheet

            /* 存入数据库操作====================================== */
            pd.put("RIGHTS", ""); // 权限
            pd.put("LAST_LOGIN", ""); // 最后登录时间
            pd.put("IP", ""); // IP
            pd.put("STATUS", "0"); // 状态

            List<Role> roleList = roleService.listAllERRoles(); // 列出所有二级角色

            pd.put("ROLE_ID", roleList.get(0).getROLE_ID()); // 设置角色ID为随便第一个
            /**
             * var0 :编号 var1 :姓名 var2 :手机 var3 :邮箱 var4 :备注
             */
            for (int i = 0; i < listPd.size(); i++ )
            {
                pd.put("USER_ID", this.get32UUID()); // ID
                pd.put("NAME", listPd.get(i).getString("var1")); // 姓名

                String USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1")); // 根据姓名汉字生成全拼
                pd.put("USERNAME", USERNAME);
                if (userService.findByUId(pd) != null)
                { // 判断用户名是否重复
                    USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1"))
                               + Tools.getRandomNum();
                    pd.put("USERNAME", USERNAME);
                }
                pd.put("BZ", listPd.get(i).getString("var4")); // 备注
                if (Tools.checkEmail(listPd.get(i).getString("var3")))
                { // 邮箱格式不对就跳过
                    pd.put("EMAIL", listPd.get(i).getString("var3"));
                    if (userService.findByUE(pd) != null)
                    { // 邮箱已存在就跳过
                        continue;
                    }
                }
                else
                {
                    continue;
                }

                pd.put("NUMBER", listPd.get(i).getString("var0")); // 编号已存在就跳过
                pd.put("PHONE", listPd.get(i).getString("var2")); // 手机号

                pd.put("PASSWORD", new SimpleHash("SHA-1", USERNAME, "123").toString()); // 默认密码123
                if (userService.findByUN(pd) != null)
                {
                    continue;
                }
                userService.saveU(pd);
            }
            /* 存入数据库操作====================================== */

            mv.addObject("msg", "success");
        }

        mv.setViewName("save_result");
        return mv;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
    }

    /* ===============================权限================================== */
    public Map<String, String> getHC()
    {
        Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
    }
    /* ===============================权限================================== */
}
